package com.pug.config.interceptor;

import com.pug.constant.PugContants;
import com.pug.result.ex.KsdValidationException;
import com.pug.service.redis.PugRedisOperator;
import com.pug.utils.ip.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 发送短信限流，一分钟只能发送一次验证码
 */
@Component
@Slf4j
public class PassportInterceptor implements HandlerInterceptor, PugContants {

    @Autowired
    private PugRedisOperator redisOperator;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取用户ip
        String userIp = IpUtils.getIpAddr(request);
        boolean isExist = redisOperator.keyIsExist(PUG_IP  + userIp);
        if (isExist) {
            log.info("短信发布频率太大!");
            throw new KsdValidationException(601, "短信发布频率太大");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
